#include "httpserver.h"

HttpServer::HttpServer(QObject *parent) :
    QThread(parent)
{
    state = Idle;
}

static struct mg_serve_http_opts s_http_server_opts;

static void ev_handler(struct mg_connection *nc, int ev, void *p)
{
    if (ev == MG_EV_HTTP_REQUEST)
    {
        //emit HttpServer::writeLog("Http Action. new request");

        printf("\n new request");

        mg_serve_http(nc, (struct http_message *) p, s_http_server_opts);
    }
}

void HttpServer::run()
{
    struct mg_mgr mgr;
    struct mg_connection *nc;
    QString uri = "";
    const char *root = NULL;
    const char *root1 = NULL;

    mg_mgr_init(&mgr, NULL);

    uri = QString::number(this->port);

    nc = mg_bind(&mgr, uri.toLatin1().constData(), ev_handler);
    if (nc == NULL)
    {
        emit writeLog("Http Action. Listen error!");
        return;
    }

    emit writeLog("Http Action. Start on ::" + QString::number(this->port) + ", Dir: " + this->dir);

    mg_set_protocol_http_websocket(nc);
    root = this->dir.toUtf8().constData();
    root1 = strdup(root);
    s_http_server_opts.document_root = strdup(root);
    s_http_server_opts.enable_directory_listing = "yes";

    printf("!!!!%s!!!", root1);

    state = Running;

    emit serverStarted();

    while(state != Waiting)
    {
        mg_mgr_poll(&mgr, 20);
    }
    mg_mgr_free(&mgr);

    state = Stopped;

    emit writeLog("Http Action. Stopped");

    emit serverStopped();

    return;
}

void HttpServer::ev_handler(struct mg_connection *nc, int ev, void *p)
{
    if (ev == MG_EV_HTTP_REQUEST)
    {
        //emit HttpServer::writeLog("Http Action. new request");

        printf("\n new request");

        mg_serve_http(nc, (struct http_message *) p, s_http_server_opts);
    }
}

void HttpServer::startServer(QString dir, int port)
{
    state = Proc;
    this->dir = QString(dir);
    this->port = port;

    emit writeLog("Action Start. dir: " + dir + ", Port: " + QString::number(port));

    this->start();
}

void HttpServer::stopServer()
{
    emit writeLog("Action Stop.");

    state = Waiting;
}
